package com.h6.crm.interceptor;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.lang.Nullable;

import com.h6.crm.entity.SysUser;
import com.h6.crm.mapper.SysRoleGroupMapper;
import com.h6.crm.mapper.SysUserMapper;
import com.h6.crm.util.Constant;
import com.h6.crm.util.pojo.ResultCode;
import com.h6.crm.util.pojo.ServiceException;
import com.h6.crm.util.pojo.UserContext;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Component
public class UserLoginInterceptor implements HandlerInterceptor {

    @Autowired
    SysUserMapper userMapper;

    @Autowired
    SysRoleGroupMapper roleGroupMapper;

    @Value("#{'${account.exclude-uris:}'.empty ? null : '${account.exclude-uris:}'.split(',')}")
    private List<String> exculdeUris;

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,
            @NonNull Object handler)
            throws Exception {

        if (checkGetLoginUser(request.getRequestURI())) {
            return true;
        }

        String token = request.getHeader(Constant.HEADER_USER_KEY);
        if (StrUtil.isBlank(token)) {
            throw new ServiceException(ResultCode.PARAM_NOT_COMPLETE2);
        }
        // 获取用户信息，包括权限信息
        SysUser userRes = userMapper.selectById(token);
        List<Integer> roleIdList = roleGroupMapper.queryRoleIdsByUserId(token);
        if (ObjectUtil.isNull(userRes)) {
            throw new ServiceException(ResultCode.ACCOUNT_NOT_EXISTS);
        }
        // 检查是否是管理员账号
        userRes.setIsAdmin(CollectionUtils.containsAny(roleIdList, Constant.ADMIN_ACCOUNT_LIST));
        UserContext.saveUser(userRes);
        // response.addHeader(Constant.HEADER_USER_ISADMIN,
        // JSONObject.toJSONString(userRes.getIsAdmin() ? 1 : 0));
        return true;
    }

    @Override
    public void postHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,
            @NonNull Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,
            @NonNull Object handler, @Nullable Exception ex)
            throws Exception {
        UserContext.removeUser();
    }

    private Boolean checkGetLoginUser(String uri) {
        return exculdeUris.contains(uri) || exculdeUris.stream().anyMatch(shortPattern -> uri.startsWith(shortPattern));
    }
}
